package yc.day0109.lottery.utils;

import java.sql.*;

public class BaseDao {
    //定义了driver url username password 静态实例
    protected static String driver;
    protected static String url;
    protected static String username;
    protected static String password;
    //Connection 数据库连接对象
    protected Connection conn;
    //PreparedStatement 预编译传输实例对象
    protected PreparedStatement pstmt;
    //ResultSet 查询结果集实例对象
    protected ResultSet rs;
    //1.建立数据库连接
    public Connection getConn(){
        driver = ConfigManager.getInstance().getProperty("oracle.driver");
        url = ConfigManager.getInstance().getProperty("oracle.url");
        username = ConfigManager.getInstance().getProperty("oracle.username");
        password = ConfigManager.getInstance().getProperty("oracle.password");
//        driver = "oracle.jdbc.driver.OracleDriver";
//        url = "jdbc:oracle:thin:@localhost:1521:orcl";
//        username = "LOTTERY";
//        password = "123456";
        try{
            //1.加载数据库驱动
            Class.forName(driver);
            //2.建立数据库连接对象
            conn = DriverManager.getConnection(url,username,password);
        }catch (Exception e){
            e.printStackTrace();
        }
        return conn;
    }
    //2.关闭数据库所有连接
    public void closeAll(ResultSet rs,PreparedStatement pstmp,Connection conn){
        try{
            if(rs != null){
                rs.close();
            }
            if(pstmp != null){
                pstmt.close();
            }
            if(conn != null){
                conn.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
    //3.定义公共的查询方法
    public ResultSet executeQuery(String sql,Object...params){
        conn = getConn();
        try{
            pstmt = conn.prepareStatement(sql);
            for(int i =0;i < params.length;i++){
                pstmt.setObject(i+1,params[i]);
            }
            rs = pstmt.executeQuery();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return rs;
    }
    //4.定义公共的增删改方法
    public int executeUpdate(String sql,Object...params){
        int result = 0;
        conn = getConn();
        try{
            pstmt = conn.prepareStatement(sql);
            for(int i =0;i < params.length;i++){
                pstmt.setObject(i+1,params[i]);
            }
            result = pstmt.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            closeAll(rs,pstmt,conn);
        }
        return result;
    }
    public static void main(String[] args) {
        BaseDao bd = new BaseDao();
        System.out.println(bd.getConn());
    }
}
